<!--
 * @Author: 赵京涛 z19472333952022@163.com
 * @Date: 2024-07-13 22:28:40
 * @LastEditors: 赵京涛 z19472333952022@163.com
 * @LastEditTime: 2024-07-13 22:28:40
 * @projectName: data_analysis_web
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" v-loading="loading.bodyLoading">
    <el-form ref="searchForm" :inline="true" :model="form" size="small" v-loading='loading.loading2'>
      <el-form-item label="开始时间">
        <el-date-picker v-model="queryParams.startTime" type="date" placeholder="选择开始时间" value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="queryParams.endTime" type="date" placeholder="选择结束时间" value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item>
        <lv-button v-show="searchFromDataList && searchFromDataList.length > 0" type="p" size="small" label="查询" icon="el-icon-search" @click="searchHandler" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-upload action="" accept=".xls, .xlsx" :before-upload="beforeUpload" :file-list.sync="fileLists" :show-file-list="false" multiple
          class="el-upload-container">
          <lv-button type="p" size="small" icon="el-icon-plus" label="新建导入任务" />
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <lv-button label="下载报送模版" type="d" size="small" icon="el-icon-download" @click="downloadDataHandler" msg="是否确认下载该任务模板?" />
      </el-col>
    </el-row>
    <el-table v-loading="loading.loading1" :data="tableList" border>
      <el-table-column align="center" width="120" label="序号">
        <template v-slot:default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="文件名" prop="attachName" align="center" />
      <el-table-column label="上传时间" prop="creationTime" align="center" />
      <el-table-column label="数据量" prop="dataSize" align="center" />
      <el-table-column label="操作" align="center" width="260">
        <template v-slot:default="scope">
          <el-link style="margin-right: 15px" type="primary" icon="el-icon-view" @click='seeTaskReportDataHandler(scope.row)'>查看</el-link>
          <el-link style="margin-right: 15px" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-link>
          <el-link type="success" icon="el-icon-bottom" @click="downloadTaskHandler(scope.row)">下载</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getTableDataList" />
    <!-- 查看数据对话框 -->
    <el-dialog v-dialogDragPlus :title="renderDataParams.title" :visible.sync="renderDataParams.show" width="80vw" append-to-body>
      <div class='renderBox-center' v-loading='loading.renderTableLoading'>
        <renderDialogTable :isShow='renderDataParams.show' :isShowThreeColumn='isShowThreeColumn' :tableHeader='headerList' :tableData='renderTableList' />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  deleteUpdateinfoData,
  getIsPortIsOneList,
  getParameterList,
  getTaskReportData,
  getUpdateInfoList,
  importSave
} from '@/api/dataReport'
import renderDialogTable from '@/components/renderDialogTable/index.vue'
import LvButton from '@/components/lvButton/index.vue'
import {
  columnNameTransformArrayAccording,
  convertObjectToNewStructure,
  filterEmpty,
  findIndexInArray,
  getIsPortIsOneDisposeDataStructure,
  sortDataBySortField,
  successMessage,
  threeColumnNameTransformDataStructure,
  transformOrder,
  useSureMessageBox,
  useTaskSuccessHeaderTable,
  useTaskSuccesTableDataList,
  warningMessage
} from '@/hooks'
import { deleteTaskSuccess, uploadFileFormatMsg, uploadFileSizeMsg } from '@/views/dataReport/json'

export default {
  components: { LvButton, renderDialogTable },
  id: 'dataSearch',
  data() {
    return {
      dataId: 0,
      pageName: '',
      total: 0,
      loading: {
        loading1: false,
        loading2: false,
        renderTableLoading: false,
        bodyLoading: false
      },
      fileType: 'xls、xlsx', // 文件类型
      fileLists: [], // 文件列表
      parameterParams: '', // 查询条件集合（json）
      tableList: [],
      queryParams: {   // 查询参数
        pageNum: 1,
        pageSize: 10,
        startTime: null,
        endTime: null
      },
      form: {}, // 搜索表单
      searchFromDataList: [], // 搜索表单列表数据
      isShowThreeColumn: false, // 是否显示三级表头数据
      headerList: [], // 动态表头
      renderTableList: [], // 动态列表数据
      renderDataParams: {
        title: '',
        show: false
      },
      listApiUrl: '' // 列表接口地址
    }
  },
  created() {
    this.$nextTick(() => {
      this.getInit()
    })
  },
  methods: {
    // 初始化获取menuCode
    getInit() {
      this.dataId = this.$route.query.id
      this.pageName = this.$route.meta.title
      this.listApiUrl = this.$route.meta.apiUrl
      this.getSearchListHandler()
    },
    // 获取查询条件数据
    async getSearchListHandler() {
      try {
        this.loading.loading2 = true
        const { code, data } = await getParameterList({ relationId: Number(this.dataId) })
        if (code === 200 && data) {
          this.searchFromDataList = sortDataBySortField(data)
          await this.getTableDataList()
        }
        this.loading.loading2 = false
      } catch (err) {
        console.log(err)
      }
    },
    // 列表数据
    async getTableDataList() {
      try {
        this.loading.loading1 = true
        this.queryParams.dataId = this.dataId
        const { code, data } = await getUpdateInfoList(this.listApiUrl, { ...this.queryParams })
        if (code === 200 && data) {
          this.total = data.total
          this.tableList = data.list
        } else {
          this.total = 0
          this.tableList = []
        }
        this.loading.loading1 = false
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 查询
     */
    async searchHandler() {
      const resRromEmpty = filterEmpty(JSON.parse(JSON.stringify(this.form)))
      this.parameterParams = convertObjectToNewStructure(resRromEmpty, this.searchFromDataList)
      await this.getTableDataList()
    },
    /**
     * 处理数组中的每个元素，根据元素的属性执行异步操作。
     *
     * @param {Array} arrItem 包含多个对象的数组，每个对象代表一个表单项。
     * @returns {Promise<{form: Object}>} 返回一个Promise，解析后得到更新后的表单对象。
     */
    async isExitIsPortHandler(arrItem) {
      // 如果数组为空或没有元素，则直接解析并返回当前的表单对象
      if (!arrItem || arrItem.length === 0) {
        return Promise.resolve({ form: this.form })
      }
      // 遍历数组中的每个元素，并为每个元素生成一个对应的异步操作Promise
      const promises = arrItem.map(async (item) => {
        // 如果元素的isPort属性为1，则执行特定逻辑
        if (item.isPort === 1) {
          if (!['jcrq-start', 'jcrq-end', 'jsrq-start', 'jsrq-end', 'start_date-start', 'start_date-end'].includes(item.fieldCode)) {
            // 如果fieldCode不是特定的几个值，则调用fetchOptionsHandler函数
            await this.fetchOptionsHandler(item)
          } else {
            // 对于特定的fieldCode，调用getIsPortIsOneList函数并更新表单值
            const response = await getIsPortIsOneList(item.value)
            if (item.fieldCode.endsWith('-start') && (!this.form[item.fieldCode] || this.form[item.fieldCode] === '') && this.form[item.fieldCode] !== null) {
              this.$set(this.form, item.fieldCode, response.data)
            } else if (item.fieldCode.endsWith('-end') && (!this.form[item.fieldCode] || this.form[item.fieldCode] === '') && this.form[item.fieldCode] !== null) {
              this.$set(this.form, item.fieldCode, response.data)
            }
          }
        } else if (item.value && item.value !== '') {
          // 如果元素的isPort属性不为1且value属性不为空，则调用getIsValueHaveHandler函数
          await this.getIsValueHaveHandler(item)
        }
      })
      // 等待所有的异步操作完成
      await Promise.all(promises)
      // 返回更新后的表单对象
      return { form: this.form }
    },
    /**
     * 如果说isPort的参数为1 就需要请求接口取值了
     * @param item
     * @returns {Promise<void>}
     */
    async fetchOptionsHandler(item) {
      try {
        const res = await getIsPortIsOneList(item.value)
        res.data && Array.isArray(res.data) && res.data.length > 0 ? this.searchFromDataList = getIsPortIsOneDisposeDataStructure(this, res.data, this.searchFromDataList, item.fieldName) : ''
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * value存在的情况下
     * @param item
     */
    getIsValueHaveHandler(item) {
      const optionList = []
      JSON.parse(item.value.replace(/'/g, '"')).forEach(r => { optionList.push({ label: r, value: r }) })
      const _info = this.searchFromDataList.find(g => g.fieldName === item.fieldName)
      _info.options = optionList
      const _idx = findIndexInArray(_info, this.searchFromDataList)
      this.$set(this.searchFromDataList, _idx, _info)
    },
    /**
     * 选择附件
     */
    async beforeUpload(newFile) {
      this.loading.bodyLoading = true
      // 检测上传的文件类型
      const testmsg = newFile.name.substring(newFile.name.lastIndexOf('.') + 1)
      // 文件类型是符合规则
      const state = this.fileType.indexOf(testmsg) > -1
      if (!state) {
        warningMessage(uploadFileFormatMsg)
        return false
      }
      const size = newFile.size / 1024 / 1024 < 50
      // 大小是否合适
      if (!size) {
        warningMessage(uploadFileSizeMsg)
        return false
      }
      const formData = new FormData()
      formData.append('file', newFile)
      formData.append('fileName', newFile.name)
      formData.append('dataId', this.dataId)
      const res = await importSave(formData)
      if (res.code === 200) {
        res.data.state === '数据正确' ? successMessage(`${res.data.state}, ${res.msg}`) : warningMessage(res.data.state)
        await this.getTableDataList()
      }
      this.loading.bodyLoading = false
    },
    /**
     * 导出数据
     */
    downloadDataHandler() {
      this.download('/reportUpload/templateDownload.do', { dataId: this.dataId }, `${this.pageName}.xlsx`)
    },
    /**
     * 删除
     */
    async handleDelete(row) {
      useSureMessageBox(`是否删除此任务?`,
        async () => {
          await deleteUpdateinfoData({ taskId: row.id })
          successMessage(deleteTaskSuccess)
          await this.getTableDataList()
        },
        () => { }
      )
    },
    /**
     * 下载任务文件
     * @param row
     */
    downloadTaskHandler(row) {
      this.download('/reportUpload/downloadTaskFile.do', { taskId: row.id }, `${row.attachName}`)
    },
    /**
     * 获取任务关联数据信息
     */
    async seeTaskReportDataHandler(row) {
      try {
        this.loading.renderTableLoading = true
        this.renderDataParams.title = row.attachName.replace(/\.(xlsx|xls|csv)$/i, "")
        this.renderDataParams.show = true
        const { code, data } = await getTaskReportData({ taskId: row.id })
        if (code === 200 && data.length > 0) {
          // 配置表头
          const _middleHeader = useTaskSuccessHeaderTable(data[0])
          const isThreeColumn = _middleHeader.some(item => item.headerThirdRow)
          _middleHeader.forEach(item => {
            if (!item.headerThirdRow) delete item.headerThirdRow
          })
          if (Array.isArray(_middleHeader) && _middleHeader[0]?.colspan && !isThreeColumn) {
            this.headerList = columnNameTransformArrayAccording(_middleHeader)
            this.headerList = transformOrder(_middleHeader, this.headerList).filter(s => s.isShow !== 0 && s.columnName !== 'id')
            this.isShowThreeColumn = false
          } else if (Array.isArray(_middleHeader) && isThreeColumn) {
            this.headerList = threeColumnNameTransformDataStructure(_middleHeader)
            this.isShowThreeColumn = true
          } else {
            this.isShowThreeColumn = false
            this.headerList = _middleHeader
          }
          // 配置表格数据
          this.renderTableList = useTaskSuccesTableDataList(data)
        } else {
          this.isShowThreeColumn = false
          this.headerList = []
          this.renderTableList = []
        }
        this.loading.renderTableLoading = false
      } catch (error) {
        console.log(error);
      }
    }
  }
}
</script>
